use std::collections::HashMap;
use tokio::fs::File;
use tokio::io;
use tokio::io::{AsyncBufReadExt, BufReader};
use crate::ltools::lfile;

pub struct Properties {
    pro_map: HashMap<String, String>,
    file_path: &'static str,
}

impl Properties {
    pub(crate) fn new() -> Self {
        return Properties {
            pro_map: HashMap::new(),
            file_path: "",
        };
    }

    /* 加载数据 */
    pub(crate) async fn load(&mut self, file_path: &'static str) -> io::Result<()> {
        self.file_path = file_path;
        match File::open(file_path).await {
            Ok(open_file) => {
                // 创建一个缓冲读取器
                let mut reader = BufReader::with_capacity(1024, open_file);

                let mut line = String::new();
                while reader.read_line(&mut line).await? > 0 {
                    let split_st: Vec<&str> = line.split("=").collect();
                    if split_st.len() < 2 {
                        continue;
                    }
                    self.pro_map.insert(split_st[0].to_string(), split_st[1].to_string());
                    line.clear(); // 清空字符串，以便下一次读取
                }

            }
            Err(_) => {

            }
        }
        Ok(())
    }

    /* 保存数据 */
    pub(crate) async fn save(&mut self) {
        let mut file_content = String::new();
        for (key, value) in self.pro_map.iter() {
            file_content.push_str(key);
            file_content.push_str("=");
            file_content.push_str(value);
            file_content.push_str("\n");
        }
        lfile::write_file_byte(self.file_path, file_content.as_bytes(), false).await.expect("插入错误");
    }

    /* 保存值 */
    pub(crate) async fn put(&mut self, key: String, value: String) {
        self.pro_map.insert(key, value);
    }

    /* 获取值 */
    pub(crate) async fn get_data(&self, key: &str) -> Option<&String> {
        self.pro_map.get(key)
    }
}


pub fn test() {
    tokio::runtime::Runtime::new().unwrap().block_on(async {
        let mut por = Properties::new();
        por.load(r"D:\cache\citc\index").await.unwrap();

        por.put("876521ss".to_string(), "12".to_string()).await;

        por.save().await;
    });
}





